package algorithm.doublePointer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// 三数之和
public class LC15 {
    public List<List<Integer>> threeSum(int[] nums) {
        // 1. 排序
        Arrays.sort(nums);
        int len = nums.length, c = 0;
        List<List<Integer>> ans = new ArrayList<>();

        // 2. 固定一个数
        while (c < len && nums[c] <= 0) {
            int n1 = nums[c];
            int target = -n1;
            // 将这个数后面的数组使用双指针算法找到相加的两个数和为 -n1
            int left = c + 1, right = len - 1;

            while (left < right) {
                int tmp = nums[left] + nums[right];
                if (tmp > target) {
                    right--;
                } else if (tmp < target) {
                    left++;
                } else {
                    List<Integer> list = new ArrayList<>();
                    list.add(n1);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    ans.add(list);
                    while (left < right &&
                            nums[left+1] == nums[left] && nums[right-1] == nums[right]) {
                        if (nums[left + 1] == nums[left]) {
                            left++;
                        }
                        if (nums[right - 1] == nums[right]) {
                            right--;
                        }
                    }
                    left++;
                    right--;
                }
            }
            while (c < len - 1 && nums[c + 1] == nums[c]) {
                c++;
            }
            c++;
        }
        return ans;
    }

    public static void main(String[] args) {
        LC15 lc15 = new LC15();

        int[] nums = new int[]{-1,0,1,2,-1,-4};
        List<List<Integer>> list = lc15.threeSum(nums);
        System.out.println(list);
    }
}
